package com.link.play.fit.ai.ui.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.widget.OverScroller
import com.link.play.fit.ai.R
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt


class RulerView(context: Context, attrs: AttributeSet) :
    View(context, attrs) {
    private val minValue = DEFAULT_MIN
    private val maxValue = DEFAULT_MAX
    private var cellWidth = 0 // 每个刻度宽度（像素）
    private var smallTickHeight = 0
    private var mediumTickHeight = 0
    private var largeTickHeight = 0
    private var rulerColor = 0
    private var pointerColor = 0
    private var textColor = 0
    private var textSize = 0f

    private var linePaint: Paint? = null
    private var textPaint: Paint? = null
    private var pointerPaint: Paint? = null
    private var scroller: OverScroller? = null
    private var velocityTracker: VelocityTracker? = null
    private var lastX = 0f
    private var currentValue = 0
    private var listener: OnValueChangeListener? = null

    init {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet) {
        // 加载自定义属性
        val a = context.obtainStyledAttributes(attrs, R.styleable.RulerView)
        rulerColor = a.getColor(R.styleable.RulerView_rulerColor, Color.GRAY)
        pointerColor = a.getColor(R.styleable.RulerView_pointerColor, Color.RED)
        textColor = a.getColor(R.styleable.RulerView_textColor, Color.BLACK)
        textSize = a.getDimension(R.styleable.RulerView_textSize, 36f)
        cellWidth = a.getDimensionPixelSize(R.styleable.RulerView_cellWidth, 50)
        smallTickHeight = a.getDimensionPixelSize(R.styleable.RulerView_smallTickHeight, 40)
        mediumTickHeight = a.getDimensionPixelSize(R.styleable.RulerView_mediumTickHeight, 60)
        largeTickHeight = a.getDimensionPixelSize(R.styleable.RulerView_largeTickHeight, 80)
        a.recycle()

        // 初始化画笔
        linePaint = Paint(Paint.ANTI_ALIAS_FLAG)
        linePaint!!.color = rulerColor
        linePaint!!.strokeWidth = 2f

        textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        textPaint!!.color = textColor
        textPaint!!.textSize = textSize
        textPaint!!.textAlign = Paint.Align.CENTER

        pointerPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        pointerPaint!!.color = pointerColor
        pointerPaint!!.strokeWidth = 4f

        scroller = OverScroller(context)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val height = (largeTickHeight + textSize + 20).toInt() // 高度根据最大刻度高度和文字调整
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val scrollX = scrollX
        val width = width
        val centerX = width / 2 // 固定指针在屏幕中央

        // 绘制刻度线（根据滚动偏移量动态计算）
        var startValue = floor(((scrollX - width) / cellWidth.toFloat()).toDouble()).roundToInt()
        var endValue = ceil(((scrollX + width * 2) / cellWidth.toFloat()).toDouble()).roundToInt()
        startValue = max(minValue.toDouble(), startValue.toDouble()).toInt()
        endValue = min(maxValue.toDouble(), endValue.toDouble()).toInt()

        for (value in startValue..endValue) {
            val x = value * cellWidth - scrollX // 刻度位置随滚动偏移
            // ... 绘制刻度线逻辑保持不变 ...
        }

        // 绘制固定指针（始终在屏幕中央）
        canvas.drawLine(centerX.toFloat(), 0f, centerX.toFloat(), height.toFloat(), pointerPaint!!)
    }


    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (velocityTracker == null) {
            velocityTracker = VelocityTracker.obtain()
        }
        velocityTracker!!.addMovement(event)

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (!scroller!!.isFinished) {
                    scroller!!.abortAnimation()
                }
                lastX = event.x
                return true
            }

            MotionEvent.ACTION_MOVE -> {
                val currentX = event.x
                val deltaX = lastX - currentX
                scrollBy(deltaX.toInt(), 0)
                lastX = currentX
                invalidate()
                return true
            }

            MotionEvent.ACTION_UP -> {
                velocityTracker!!.computeCurrentVelocity(1000)
                val velocityX = velocityTracker!!.xVelocity
                scroller!!.fling(
                    scrollX, 0,
                    -velocityX.toInt(), 0,
                    minValue * cellWidth, maxValue * cellWidth,
                    0, 0,
                    cellWidth / 2, 0
                )
                invalidate()
                velocityTracker!!.recycle()
                velocityTracker = null
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    override fun computeScroll() {
        if (scroller!!.computeScrollOffset()) {
            scrollTo(scroller!!.currX, 0)
            notifyValueChanged()
            invalidate()
        }
    }

    override fun scrollTo(x: Int, y: Int) {
        // 限制滚动范围确保指针始终有效
        var x = x
        x = max(
            (minValue * cellWidth).toDouble(),
            min(x.toDouble(), (maxValue * cellWidth).toDouble())
        )
            .toInt()
        super.scrollTo(x, y)
    }

    private fun notifyValueChanged() {
        var newValue = (scrollX + width / 2) / cellWidth
        newValue =
            max(minValue.toDouble(), min(newValue.toDouble(), maxValue.toDouble()))
                .toInt()
        if (newValue != currentValue && listener != null) {
            listener!!.onValueChanged(newValue)
        }
        currentValue = newValue
    }

    fun setOnValueChangeListener(listener: OnValueChangeListener?) {
        this.listener = listener
    }

    interface OnValueChangeListener {
        fun onValueChanged(value: Int)
    }

    companion object {
        private const val DEFAULT_MIN = 0
        private const val DEFAULT_MAX = 800
    }
}